package org.duang.kit;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.duang.config.Config;
import org.duang.db.annotation.Host;
import org.duang.db.annotation.ThumbHost;
import org.duang.db.mongo.parser.encode.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HostKit {

	private static Logger logger = LoggerFactory.getLogger(HostKit.class);
	private static String FILE_HOST = "";
	private static String THUMBNAIL_FILE_EXTVALUE = "";
	
	private static void addHost(Object obj, Field field, Object value){
		if(!"oss".equalsIgnoreCase(Config.getUploadFileSite())) return;
		initHostValue(field);
		if(ToolsKit.isNotEmpty(FILE_HOST) && ToolsKit.isNotEmpty(value)){			
			ObjectKit.setField(obj, field.getName(), addValue(value.toString()));
		}
	}
    
	private static void addHosts(Object obj, Field field, List<String> list){
    	if(list == null) return;
    	if(isFileHost(field) || isThumbFileHost(field)){    	
    		for(int i=0; i<list.size(); i++){
    			initHostValue(field);
    			list.set(i,addValue(list.get(i).toString()));
    		}
    		ObjectKit.setField(obj, field.getName(), list);
    	}
    }
    
	private static void addHosts(Object obj, Field field, Set<String> set){
    	if(set == null) return;
    	if(isFileHost(field) || isThumbFileHost(field)){
    		String[] strs = set.toArray(new String[set.size()]);
    		set.clear();
    		for(int i=0; i<strs.length; i++){
    			initHostValue(field);
    			set.add(addValue(strs[i]));
    		}
    		ObjectKit.setField(obj, field.getName(), set);
    	}
    }
	
    
    private static boolean isFileHost(Field field) {
    	return field.isAnnotationPresent(Host.class);
    }
    
    private static boolean isThumbFileHost(Field field) {
    	return field.isAnnotationPresent(ThumbHost.class);
    }
    
    private static void initHostValue(Field field){
    	clearConstValue();
    	if(isFileHost(field)) FILE_HOST = Config.getFileHostSite();
		if(isThumbFileHost(field) ){
			FILE_HOST = Config.getThumbnailHostSite();
			ThumbHost thumbHost = field.getAnnotation(ThumbHost.class);
			THUMBNAIL_FILE_EXTVALUE = ToolsKit.isEmpty(thumbHost.extvalue()) ? Config.getThumbnailHostSiteExt() : thumbHost.extvalue(); 
		}
    }
    
    private static void clearConstValue(){
    	FILE_HOST = "";
    	THUMBNAIL_FILE_EXTVALUE = "";
    }
    
    /**
     * 添加后的值
     * @param field
     * @param value
     * @return
     */
    private static String addValue(String value){
    	if(ToolsKit.isNotEmpty(value) && value.indexOf("http://") == -1){
    		value = value.startsWith("/") ? value : "/" + value;
    		value = FILE_HOST + value + THUMBNAIL_FILE_EXTVALUE;
    	}
    	return value;
    }
    
    /**
     * 添加域名
     * @param obj		要添加域名字符串的对象
     * @param field		要添加域名字符串的字段
     * @param value		添加域名字符串前的值
     */
    @SuppressWarnings("unchecked")
	public static void addHostSite(Object obj, Field field, Object value){
    	if(null == value) return;
		Class<?> fieldType = field.getType();
		if(DataType.isString(fieldType)){					
			HostKit.addHost(obj, field, value);
		} else if(DataType.isListType(fieldType)){
			List<String> list = (List<String>)value;
			HostKit.addHosts(obj, field, list);
		} else if(DataType.isSetType(fieldType)){
			Set<String> set = (Set<String>)value;
			HostKit.addHosts(obj, field, set);
		}
	}
    
    
   
    /**
     * 删除域名
     * @param field		删除域名字符串的字段
     * @param encoder	删除域名的解释对象
     * @return	删除域名的内容值
     */
    @SuppressWarnings("unchecked")
	public static Object removeHostSite(Field field, Encoder encoder) {
    	Object value  = encoder.getValue();
    	if(!"oss".equalsIgnoreCase(Config.getUploadFileSite())) return value;
    	Class<?> fieldType = encoder.getField().getType();
    	Object safeObj = value;
    	try{
	    	if(fieldType.equals(String.class)){
				safeObj = removeHost(field, (String)value);			// 去掉指定有@Host及@ThumbnHost注解的字段
			} 
	    	
	    	if(isFileHost(field) || isThumbFileHost(field)){
		    	if(fieldType.equals(List.class)){
					List<String> list = (List<String>)value;
					safeObj = removeHosts(field, list);	
				} else if (fieldType.equals(Set.class)){
					Set<String> list = (Set<String>)value;
					safeObj = removeHosts(field, list);	
				}
	    	}
    	} catch (Exception ex){logger.error(ex.getMessage(), ex);}
    	return safeObj;
    }	
    
    
    private static String replaceValue(String replaceString, String value) {
    	if(ToolsKit.isNotEmpty(value) && value.indexOf(replaceString) != -1){
    		value = value.replace(replaceString, "");
    	}
    	return value;
    }
    	
    private static Object removeHost(Field field, Object value) {
    	if(DataType.isString(value.getClass())){
	    	if(isFileHost(field)){
	    		value = replaceValue(Config.getFileHostSite(), value+"");
	    	}
	    	if(isThumbFileHost(field)){
	    		value = replaceValue(Config.getThumbnailHostSite(), value+"").replace(Config.getThumbnailHostSiteExt(), "");
	    	}
    		value = ToolsKit.getSafeValue(value);	// 将Html及js字符串替换成安全字符
    	}
    	return value;
    }
    private static Object removeHosts(Field field, Collection<String> coll) {
    	if(null == coll) return coll;
    	String[] arr = coll.toArray(new String[coll.size()]);
    	coll.clear();
		for(String value : arr){
			coll.add(removeHost(field, value).toString());
		}
    	return coll;
    }
}
